﻿// ------------------------------------------------------------------------------------------------
//  <copyright file="DSortedList.cs" company="Iveely">
//    Copyright (c) Iveely Liu.  All rights reserved.
//  </copyright>
//  
//  <Create Time>
//    03/02/2013 21:59 
//  </Create Time>
//  
//  <contact owner>
//    liufanping@iveely.com 
//  </contact owner>
//  -----------------------------------------------------------------------------------------------

#region

using System;
using System.Collections.Generic;
using System.Globalization;

#endregion

namespace IveelySE.Common
{
    /// <summary>
    ///   （带合并方法）排序泛型列表
    /// </summary>
    [Serializable]
    public class DSortedList : List<double>
    {
        public DSortedList(IEnumerable<double> collection)
        {
            foreach(double item in collection)
            {
                this.Add(item);
            }
        }

        public DSortedList()
        {
        }

        /// <summary>
        ///   插入
        /// </summary>
        /// <param name="item"> </param>
        public new void Add(double item)
        {
            int position = this.BinarySearch(item);
            try
            {
                position = position > -1 ? position : ~position;
                if(Math.Floor(this[position]) == Math.Floor(item))
                {
                    double x = double.Parse("0." + item.ToString(CultureInfo.InvariantCulture).Split('.')[1]);
                    this.Insert(position, this[position] + x);
                    this.RemoveAt(position + 1);
                }
                else
                {
                    base.Add(item);
                }
                //}
            }
            catch
            {
                base.Add(item);
            }
            finally
            {
                this.Sort();
            }
        }

        public void Modify(double item, int index)
        {
            this.RemoveAt(index);
            this.Add(item);
        }
    }
}